//
//  SearchController.m
//  Words2
//
//  Created by Mathieu on 2/10/06.
//  Copyright 2006 __MyCompanyName__. All rights reserved.
//

#import "SearchController.h"
#import "WordsAppDelegate.h"
#import "WordMO.h"
#import "GroupsArrayController.h";
#import "DefinitionsArrayController.h"
#import "BlobArrayController.h"
#import "WordMO.h"
#import "Blob.h"
#import "DefinitionMO.h"
#import "LanguageMO.h"

@implementation SearchController

- (void)awakeFromNib {
	//register for notifications
	isSearching = NO;
	wordWasAdded = NO;
	[self registerAsObserver];
	[super awakeFromNib];
}

- (void)registerAsObserver
{
    [self addObserver:self
		   forKeyPath:@"arrangedObjects"
			  options:(NSKeyValueObservingOptionNew |
					   NSKeyValueObservingOptionOld)
			  context:NULL];
}


- (void)observeValueForKeyPath:(NSString *)keyPath
					  ofObject:(id)object 
                        change:(NSDictionary *)change
                       context:(void *)context 
{
    if (object == self && [keyPath isEqual:@"arrangedObjects"]) {
		//if we are currently searching for something: ie, there is a string in the search field, and 
		//if there is nothing in the array controller, switch to definingWords view and begin looking up words if needed.
		if(([[searchFieldCell stringValue] length] != 0) && (isSearching == NO)){
			NSLog(@"Open the searchView");
			isSearching = YES;
			// set the bindings of the definitions and blob arrayControllers to the selection of self, 
			// so that the definitions of objects selected in OUR array controller are reflected in the views bound to 
			// those controllers.
			NSLog(@"Changing bindings on def controller");
			[definitionArrayController unbind:@"contentSet"];
			//[definitionArrayController unbind:@"filterPredicate"];
			[definitionArrayController bind:@"contentSet" toObject:self withKeyPath:@"selection.definitions" options:nil];
			NSLog(@"Changing bindings on blob controller");
			[blobArrayController unbind:@"contentSet"];
			//[blobArrayController unbind:@"filterPredicate"];
			[blobArrayController bind:@"contentSet" toObject:self withKeyPath:@"selection.blobs" options:nil];
			
			[largeWordView unbind:@"value"];
			[largeWordView bind:@"value" toObject:self withKeyPath:@"selection.word" options:nil];
			[smallWordView unbind:@"value"]; 
			[smallWordView bind:@"value" toObject:self withKeyPath:@"selection.word" options:nil];

			[wordsTabView selectTabViewItemWithIdentifier:@"WordSearch"];
		}
		
		//OK, so we are searching, and we have a word that isn't found in the user's words, so we're going to start looking for a definition
		if(([[searchFieldCell stringValue] length] != 0) && 
		   ([[self arrangedObjects] count] == 0) &&
		   (isSearching == YES))
		 {
			NSLog(@"Nothing found, switching to the add word view");
			if(tempWord == nil){
				tempWord = [[NSEntityDescription insertNewObjectForEntityForName:@"Word" inManagedObjectContext:[[NSApp delegate] managedObjectContext]] retain];
			}
			[searchResultMessage setStringValue:@""];
			[tempWord setValue:[searchFieldCell stringValue] forKey:@"word"];
			[tempWord setValue:[[NSApp delegate] currentlySelectedLanguage] forKey:@"language"];
			[self disableButtons]; //we'll clean up the interface so that the definitions stand out nice and clear.

			//clear previously found definitions for this temp word (if any)
			NSSet *defs = [tempWord mutableSetValueForKey:@"definitions"];
			NSEnumerator *defEnum = [defs objectEnumerator];
			DefinitionMO *neeeeeckst;
			while(neeeeeckst = [defEnum nextObject]){
				[[[NSApp delegate] managedObjectContext] deleteObject:neeeeeckst];
			}
			
			NSSet *blobs = [tempWord mutableSetValueForKey:@"blobs"];
			NSEnumerator *blobEnum = [blobs objectEnumerator];
			Blob *andneeeeeckst;
			while(andneeeeeckst = [blobEnum nextObject]){
				[[[NSApp delegate] managedObjectContext] deleteObject:andneeeeeckst];
			}
			[addToWordsMessage setStringValue:[NSString stringWithFormat:@"'%@' wasn't found in any where in your Words. \n\nSearching dictionaries set to lookup words in %@ for definitions...", 
				[tempWord valueForKey:@"word"], 
			[[[NSApp delegate] currentlySelectedLanguage] valueForKey:@"name"]]];
			
			
			//and start a search for this word
			bool searchResult = [[NSApp delegate] defineWord:tempWord];
			if(!searchResult){
				[searchResultMessage setStringValue:[NSString stringWithFormat:@"Nothing found in %@", [[[NSApp delegate] currentlySelectedLanguage] valueForKey:@"name"]]];
			}else{
				[searchResultMessage setStringValue:@"Definitions found!"];
			}
			
			[wordsTabView selectTabViewItemWithIdentifier:@"NoWordsFound"];
			NSLog(@"Defining the word %@", [tempWord valueForKey:@"word"]);

		}
		//add another one here- if there's only one showing, and it's the same as the search string, then increment the count
		
		//Nope, we're not searching for anything anymore, so Let's pack up the interface and get back to the plain view.
		else if (([[searchFieldCell stringValue] length] == 0) && (isSearching == YES)){
			NSLog(@"Not searching anymore. Back to main view.");
			[wordsTabView selectTabViewItemWithIdentifier:@"WordTableView"];
			[self setBindingsBack];
			
			isSearching = NO;
			if(wordWasAdded == NO) // then delete the temp word from the moc
			 {
				[[[NSApp delegate] managedObjectContext] deleteObject:tempWord];
			 }
			[tempWord release]; tempWord = nil; //release the searchController's hold on the word
			[self enableButtons];
			wordWasAdded = NO;
		}
		
		
		// the same change
		[super observeValueForKeyPath:keyPath
							 ofObject:object 
							   change:change 
							  context:context];
	}
}

-(void)setBindingsBack{
	//set the bindings back to their rightful owners.
	NSLog(@"Unbinding Objects and returning them to their rightful owners.");
	[definitionArrayController unbind:@"contentSet"];
	[blobArrayController unbind:@"contentSet"];
	[definitionArrayController bind:@"contentSet" toObject:wordsArrayController withKeyPath:@"selection.definitions" options:nil];
	[blobArrayController bind:@"contentSet" toObject:wordsArrayController withKeyPath:@"selection.blobs" options:nil];
	[largeWordView unbind:@"value"];
	[largeWordView bind:@"value" toObject:wordsArrayController withKeyPath:@"selection.word" options:nil];
	[smallWordView unbind:@"value"]; 
	[smallWordView bind:@"value" toObject:wordsArrayController withKeyPath:@"selection.word" options:nil];
	
}

-(IBAction)addWordFromWordNotFoundView:(id)sender{
	NSLog(@"Setting the language of temp word to: %@", [[[NSApp delegate] currentlySelectedLanguage] valueForKey:@"name"]);
	[tempWord setValue:[[NSApp delegate] currentlySelectedLanguage] forKey:@"language"];
	[tempWord setValue:[searchFieldCell stringValue] forKey:@"word"];
	
	[wordsTabView selectTabViewItemWithIdentifier:@"WordTableView"];
	[groupArrayController setSelectionToLibrary];
	[wordsArrayController insertObject:tempWord atArrangedObjectIndex:0];
	wordWasAdded = YES; // set the flag to tell the array controller not to delete the temp word from the moc.

	//get out of the search context
	isSearching = NO;
	[self setBindingsBack];
	[self enableButtons];
	[searchFieldCell setStringValue:@""];
	[tempWord release]; tempWord = nil; //release the searchController's hold on the word
}


-(void)enableButtons{
	[addDefButton setHidden:NO];
	[delDefButton setHidden:NO];
	[addBlobButon setHidden:NO];
	[delBlobButton setHidden:NO];
	[addWordButton setHidden:NO];
	[deleteWordButton setHidden:NO];
	[defineAllButton setHidden:NO];
	
	[recordDefButton setEnabled:YES];
	[recordWordButton setEnabled:YES];
	[playDefRecButton setEnabled:YES];
	[playWordRecButton setEnabled:YES];
	[deleteWordRecButton setEnabled:YES];
	[deleteDefRecButton setEnabled:YES];
	
	[groupsTableView setHidden:NO];
	
}
//this is called when we're purely looking for an as yet unencountered word by the user.
-(void)disableButtons{
	[addDefButton setHidden:YES];
	[delDefButton setHidden:YES];
	[addBlobButon setHidden:YES];
	[delBlobButton setHidden:YES];
	[addWordButton setHidden:YES];
	[deleteWordButton setHidden:YES];
	[defineAllButton setHidden:YES];

	
	[recordDefButton setEnabled:NO];
	[recordWordButton setEnabled:NO];
	[playDefRecButton setEnabled:NO];
	[playWordRecButton setEnabled:NO];
	[deleteWordRecButton setEnabled:NO];
	[deleteDefRecButton setEnabled:NO];
	
	[groupsTableView setHidden:YES];
}


@end
